//
//  DeviceViewController.swift
//  hamaton-app
//
//  Created by intyt on 2024/3/26.
//

import UIKit
import CoreBluetooth
import SnapKit
import Toast_Swift

private let Service_UUID: String = "CDD1"
private let Characteristic_UUID: String = "CDD2"

private var equipmentName_prefix: String = ""
// 接收机设置参数
var equipmentData: Data?
// 显示器设置参数
var xianshiqiInfo: Data?

enum HamatonBluetoothState {
    case  nomalState // 初始状态
    case  stateScanState // 可以开始扫描
    case  scanState // 正在扫描
    case  scanStopState // 停止扫描
    case  linkState // 连接状态
}
// 使用委托模式定义协议
protocol SecondViewControllerDelegate: AnyObject {
    // 保存接收机设置
    func saveDeviceSetting(_ hexString: String)
    // 保存挂车数量
    func saveTrailerNum(_ hexString: String, _ carNum: String)
}
// 上下挂设置委托协议
protocol HamatonUpAndDownDelegate: AnyObject {
    func didUpAndDownSave(_ trailersNumOption: trailerNumModel)
}
// 阈值设置委托协议
protocol HamatonThresholdSettingDelegate: AnyObject {
    func saveThresholdSetting(_ thresholdSettingModel: ThresholdSettingModel)
}
// 轮胎参数设置委托协议
protocol HamatonWheelSensorDelegate: AnyObject {
    // 保存轮胎传感器
    func saveWheelSensor(_ tyreSetting: TyreSettingModel)
    // 擦除某个轮胎
    func cancelWheelSensor(_ tyreSetting: TyreSettingModel)
}
// 轮胎展示设置委托协议
protocol HamatonTyreDisplayDelegate: AnyObject {
    // 获取轮胎传感器
    //func getTyreSensor(_ tyreNum: String)
}

// 固件升级委托协议
protocol HamatonFirmwareUpgradeDelegate: AnyObject {
    // 升级
    func firmwareUpgradeSave0(_ url: URL)
    // 升级成功后断开连接
    func upgradeSuccessDisconnect()
}

// 显示器设置委托协议
protocol HamatonXsqDisplayDelegate: AnyObject {
    // 保存设置
    func xsqDisplaySave(_ xsqModel: XsqDisplaySettingModel)
}

class HamatonDeviceViewController: HamatonBaseViewController, SecondViewControllerDelegate, HamatonUpAndDownDelegate, HamatonThresholdSettingDelegate, HamatonWheelSensorDelegate, HamatonTyreDisplayDelegate, HamatonFirmwareUpgradeDelegate, HamatonXsqDisplayDelegate {
    //发现的蓝牙外设
    var discoveredPeripheralsArr :[HamatonBluethoothCellModel] = []
    // 挂车数量
    var trailerNumber: String = "0"
    // 当前是哪个挂车
    var currentTrailer: Int = 1
    var dataToSend: [String] = [] // 要发送的数据数组
//    var sendDataIndex = 0 // 发送数据的索引
    var currentClickType: Int = 1 // 当前点击哪个按钮1系统参数设置2轮胎参数设置3展示4固件升级5诊断 6显示器设置
    var carTyreModel: CarTyreModel = CarTyreModel() // 轮胎位置
    var carTyreBindNum: Int = 0 // 已绑定传感器的个数
    var getTyreTpmsClickType: Int = 1 // 获取轮胎阈值 1阈值设置2轮胎绑定3刷新所有已绑定的轮胎阈值4未绑定轮胎进入绑定之前5轮胎参数展示
    var currentTyreStr: String = "" // 当前擦除的轮胎编号
    var thresholdSettingStr: String = "" // 阈值设置字符串
    var allThresholeSettingArray: [String] = [] // 所有已绑定的轮胎参数
    var bindList: [String] = [] // 所有已绑定的轮胎的胎位号
    
    var getThresholeSettingNum: Int = 0 // 循环请求轮胎参数的次数
    var setTyreThresholeNum: Int = 0 // 循环设置轮胎阈值参数的次数
    var currentClickTyreStr: String = "" // 当前点击的轮胎号
    var currentLinkDeviceMac: String = "" // 当前连接的蓝牙设备MAC
    var allBindTyreData: [Data] = [] // 所有已绑定的轮胎参数（轮位展示用）
    var fileUpNum: Int = 0 // 文件切割成了几份上传几次
    var selectedFileURL: URL? = URL(string: "")// 当前要上传文件的URL
    
    // var searchCarIdType: Int = 0 // 获取车辆id 1接收机 2显示器
    var xianshiqiMac: String = "" // 显示器头车MAC
    
    
    var tnModel: trailerNumModel = trailerNumModel()
    private var addModel: HamatonCarSettingViewModel = HamatonCarSettingViewModel()
    
    lazy var centralManager:CBCentralManager = {
        let c =  CBCentralManager.init()
        return c
    }()
    
    
    // 连接的设备
    private var connectedPeripheral: CBPeripheral?
    
    private var characteristic: CBCharacteristic? // 平时使用的服务
    private var characteristicUp: CBCharacteristic? // 固件升级使用的服务
    private var characteristicUp2: CBCharacteristic? // 固件升级使用的服务2
    
    private var bluetoothState: HamatonBluetoothState = .nomalState {
        didSet {
            print("\(bluetoothState)")
            switch bluetoothState {
            case .nomalState:
                stateBtn.setTitle(NSLocalizedString("扫描设备", tableName: "HamatonLocalizable", comment: ""), for: .normal)
                tableView.isHidden = false
                deviceConnetedView.isHidden = true
                break
            case .stateScanState:
                stateBtn.setTitle(NSLocalizedString("扫描设备", tableName: "HamatonLocalizable", comment: ""), for: .normal)
                tableView.isHidden = false
                deviceConnetedView.isHidden = true
                break
            case .linkState:
                stateBtn.setTitle(NSLocalizedString("断开连接", tableName: "HamatonLocalizable", comment: ""), for: .normal)
                deviceConnetedView.isHidden = false
                tableView.isHidden = true
                discoveredPeripheralsArr.removeAll()
                break
            case .scanState:
                stateBtn.setTitle(NSLocalizedString("停止扫描", tableName: "HamatonLocalizable", comment: ""), for: .normal)
                tableView.isHidden = false
                deviceConnetedView.isHidden = true
                break
            case .scanStopState:
                stateBtn.setTitle(NSLocalizedString("停止扫描", tableName: "HamatonLocalizable", comment: ""), for: .normal)
                tableView.isHidden = false
                deviceConnetedView.isHidden = true
                break
            }
        }
    }
    // 可连接的蓝牙列表
    lazy var tableView: UITableView = {
        let tv = UITableView.init(frame: CGRect.zero, style: .grouped)
        tv.backgroundColor = UIColor.white
        tv.separatorStyle = .none
        tv.delegate = self
        tv.dataSource = self
        tv.register(HamatonBluetoothTitleTableViewCell.self, forCellReuseIdentifier: "HamatonBluetoothTitleTableViewCell")
        view.addSubview(tv)
        return tv
    }()
    
    // 连接设备成功后的页面
    lazy var deviceConnetedView: HamatonDeviceConnectedView = {
        let view = HamatonDeviceConnectedView()
        view.isUserInteractionEnabled = true
        view.delegate = self
        return view
    }()
    
    lazy var stateBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.backgroundColor = .clear
        button.setTitle(NSLocalizedString("扫描设备", tableName: "HamatonLocalizable", comment: ""), for: .normal)
        button.setTitleColor(UIColor(hex6: 0xFFFFFF, alpha: 1.0), for: .normal)
        button.backgroundColor  = Theme.Color.Background.main
        button.layer.masksToBounds = true
        button.layer.cornerRadius = 5
        button.addTarget(self, action: #selector(onClickButton), for: .touchUpInside)
        view.addSubview(button)
        return button
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        view.backgroundColor = Theme.Color.Background.default
        navigationItem.title = "设备"
        stateBtn.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(60)
            make.height.equalTo(40)
            make.width.equalTo(160)
            make.centerX.equalToSuperview()
        }
        tableView.snp.makeConstraints { make in
            make.top.equalTo(stateBtn.snp.bottom).offset(20)
            
            make.left.right.bottom.equalToSuperview()
        }
        view.addSubview(deviceConnetedView)
        deviceConnetedView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(120)
            make.right.equalToSuperview()
            make.width.equalToSuperview()
            make.height.equalTo(560)
        }
        
        self.centralManager.delegate = self
    }
    
    
    // 开始扫描
    private func startScanForPeripherals() {
        bluetoothState = .scanStopState
        self.centralManager.scanForPeripherals(withServices: nil, options: nil)
    }
    
    // 停止扫描
    private func stopScanForPeripherals() {
        bluetoothState = .stateScanState
        self.centralManager.stopScan()
    }
    
    
    ///连接外设
    func connectBluetooth(peripheral: CBPeripheral?, mac: String) {
        if peripheral != nil {
            self.connectedPeripheral = peripheral
            self.currentLinkDeviceMac = mac
            self.centralManager.connect(self.connectedPeripheral!, options: nil)
        }
    }
    
    // 断开连接
    func disconnectLink() {
        print("断开连接方法")
        self.centralManager.cancelPeripheralConnection(self.connectedPeripheral!)
        // 断开后需清空之前的订阅
        self.connectedPeripheral = nil
        self.characteristic = nil
        self.startScanForPeripherals()
        
    }

    // 获取
    private func readValueForCharater(_ sender: Any) {
        self.connectedPeripheral?.readValue(for: self.characteristic!)
    }
    
    // 写入数据
    private func writeMessage(_ message: String?) {
        let hexString = "3A"
        if let decimalValue = UInt8(hexString, radix: 16) {
            // 创建包含十进制数值的 Data 对象
                let data = Data([decimalValue])
            // 检查 peripheral 和 characteristic 是否存在
            
            guard let peripheral = self.connectedPeripheral else {
                print("Peripheral为空")
                return
            }
            guard let characteristic = self.characteristic else {
                print("Characteristic 为空")
                return
            }
            print("写入的data")
                // 写入数据到蓝牙特征
            self.connectedPeripheral?.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
        }
    }
    
    @objc func onClickButton() {
        if bluetoothState == .stateScanState {
            startScanForPeripherals() // 开始扫描
        }
        else if bluetoothState == .linkState {
            disconnectLink() // 断开连接
        }
        else if bluetoothState == .scanStopState {
            stopScanForPeripherals() // 停止扫描
        }
    }
    
}

extension HamatonDeviceViewController: CBCentralManagerDelegate {
    
    // 检测蓝牙是否可用
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch central.state {
        case .unknown:
            print("CBCentralManager state:unknown")
            break
        case .resetting:
            print("resetting")
            break
        case .unsupported:
            print("unsupported")
            break
        case .unauthorized:
            print( "unauthorized")
            break
        case .poweredOn:
            print("poweredOn")
            ///扫描设备 -扫描所有设备
            bluetoothState = .stateScanState
            break
        case .poweredOff:
            print("CBCentralManager state:", "poweredOff")
            break
        default:
            print("未知错误")
        }
    }
    
    ///发现设备
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        if (peripheral.name != nil && (peripheral.name?.prefix(6) == "NLP200" || peripheral.name?.prefix(6) == "DRX110")) {
            var mac = ""
            if let data = advertisementData["kCBAdvDataManufacturerData"] as? Data {
                mac = String(format: "%02X", data[2]) + ":" + String(format: "%02X", data[3]) + ":" + String(format: "%02X", data[4]) + ":" + String(format: "%02X", data[5]) + ":" + String(format: "%02X", data[6]) + ":" + String(format: "%02X", data[7])
            }
            //过滤存在的蓝牙外设
            var isExisted = false
            for model in discoveredPeripheralsArr {
                if (model.peripheral.identifier == peripheral.identifier){
                    isExisted = true
                    break
                }
            }
            if !isExisted {
                var stateLink: HamatonLinkState  = .noLinking
                if(peripheral.identifier == self.connectedPeripheral?.identifier) {
                    stateLink = .isLinking
                }
                let modelP = HamatonBluethoothCellModel(peripheral: peripheral, mac: mac, state: stateLink)
                discoveredPeripheralsArr.append(modelP)
                tableView.reloadData()
            }
        }
    }
    
    ///连接设备成功
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        print("连接设备成功")
        self.connectedPeripheral = peripheral
        peripheral.delegate = self
        bluetoothState = .linkState
        // 给已连接页面的设备名称和设备编号赋值
        deviceConnetedView.deviceName.text = peripheral.name
        if peripheral.name?.prefix(6) == "NLP200" { // 接收机
            deviceConnetedView.setBtn.isHidden = false
            deviceConnetedView.carBtn.isHidden = false
            deviceConnetedView.displayBtn.isHidden = false
            deviceConnetedView.upgradesBtn.isHidden = false
            deviceConnetedView.diagnosisBtn.isHidden = false
            deviceConnetedView.XsqDisplayBtn.isHidden = true
            deviceConnetedView.XsqUpgradesBtn.isHidden = true
        } else { // 显示器
            deviceConnetedView.setBtn.isHidden = true
            deviceConnetedView.carBtn.isHidden = true
            deviceConnetedView.displayBtn.isHidden = true
            deviceConnetedView.upgradesBtn.isHidden = true
            deviceConnetedView.diagnosisBtn.isHidden = true
            deviceConnetedView.XsqDisplayBtn.isHidden = false
            deviceConnetedView.XsqUpgradesBtn.isHidden = false
        }
        // deviceConnetedView.deviceCode.text = peripheral.identifier.uuidString
        
        deviceConnetedView.deviceCode.text = currentLinkDeviceMac
        // 停止扫描
        self.centralManager.stopScan()
        //开始寻找Services。传入nil是寻找所有Services
        peripheral.discoverServices(nil)
    }
    ///连接设备失败
    func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
        print("连接失败:\(error.debugDescription)")
    }
    ///断开连接
    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
        print("断开连接")
        ///// 如果是已连接状态断开后重新连接
        if(bluetoothState == .linkState) {
            central.connect(peripheral, options: nil)
        }
        //central.connect(peripheral, options: nil)
    }
    
}

// 连接蓝牙设备处理
extension HamatonDeviceViewController: CBPeripheralDelegate {
    /** 发现服务 */
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        if let services = peripheral.services {
            for service: CBService in services {
                print("外设中的服务有：\(service)")
                // 这里修改 UDID
                if service.uuid.uuidString == "6BCB7A00-38CE-40A6-9AB5-36142F618183" {
                    //本例的外设中只有一个服务
                    peripheral.discoverCharacteristics(nil, for: service)
                }
                if service.uuid.uuidString == "1D14D6EE-FD63-4FA1-BFA4-8F47B42119F0" {
                    //本例的外设第二个服务
//                    upService = service
                    peripheral.discoverCharacteristics(nil, for: service)
                }
            }
        }
    }
    
    /** 发现特征 */
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        
        if error != nil{
            // 错误
            print("错误")
            print(error?.localizedDescription)
        } else {
            print("发现特征")
            for characteristic: CBCharacteristic in service.characteristics! {
                let propertie = characteristic.properties
                // 订阅
                if propertie == CBCharacteristicProperties.indicate {
                    print("订阅订阅")
                    print(CBCharacteristicProperties.indicate)
                    print(characteristic)
                    peripheral.setNotifyValue(true, for: characteristic)
                }
                if characteristic.uuid.uuidString == "984227F3-34FC-4045-A5D0-2C581F81A153" { // 接收机｜｜显示器
                    self.characteristicUp2 = characteristic
                }
                // 写
                if propertie == CBCharacteristicProperties.write {
                    //char[3]
                    // 这里修改 UDID
                    print("写写写")
                    print(propertie)
                    print(characteristic.uuid.uuidString)
                    if characteristic.uuid.uuidString == "6BCB7B01-38CE-40A6-9AB5-36142F618183" {
                        self.characteristic = characteristic
                    }
                    
                    if characteristic.uuid.uuidString == "F7BF3564-FB6D-4E53-88A4-5E37E0326063" {
                        self.characteristicUp = characteristic
                    }
                }
                
                // 读
                if propertie == CBCharacteristicProperties.read {
                    print("读读读")
                    print(propertie)
                    peripheral.readValue(for: characteristic)
                }
            }
        }
    }
    
    /** 订阅状态 */
    func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
        if let error = error {
            print("订阅失败: \(error)")
            return
        }
        if characteristic.isNotifying {
            print("订阅成功")
        } else {
            print("取消订阅")
        }
    }
    
    /** 接收到数据 */
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        if let value = characteristic.value {
            print("Received data: \(value)")
            let data = characteristic.value
            print(data!)
            print(String(format: "%02X", data![0]))
            print(String(format: "%02X", data![1]))
            if String(format: "%02X", data![0]) == "08" {  // 诊断数据
                print("收到诊断数据")
                deviceInit(data)
            } else if  String(format: "%02X", data![0]) == "05" { // 蓝牙名称
                print("收到蓝牙名称")
                equipmentNameInit(data)
            } else if  String(format: "%02X", data![0]) == "02"&&String(format: "%02X", data![1]) == "31" { // 蓝牙名称设置成功
                print("蓝牙名称修改成功")
                self.centralManager.cancelPeripheralConnection(self.connectedPeripheral!)
                self.view.makeToast("蓝牙名称修改成功，需重新进行连接", duration: 3.0, position: .center)
                // 延时执行时间，单位为秒
                let delayInSeconds: TimeInterval = 3.0
                DispatchQueue.main.asyncAfter(deadline: .now() + delayInSeconds) {
                    // 在延时之后执行的代码
                    self.disconnectLink()
                }
            } else if  String(format: "%02X", data![0]) == "03"&&String(format: "%02X", data![1]) == "31" { // 蓝牙名称设置失败
                print("蓝牙名称修改失败")
                self.view.makeToast("蓝牙名称修改失败，请重新进行修改", duration: 3.0, position: .center)
            } else if String(format: "%02X", data![0]) == "04" {
                print("收到接收机配置参数")
                if currentClickType == 1 {
                    equipmentData = data
                    self.getTrailerNum() // 获取挂车数量
                } else if currentClickType == 2 {
                    equipmentData = data
                    self.getTyrePosition() // 获取轮胎位号
                } else if currentClickType == 3 {
                    equipmentData = data
                    self.getTyrePosition() // 获取绑定传感器的轮胎信息
                } else if currentClickType == 6 { // 收到显示器配置参数
                    getXsqSettingInfo(data)
                }
            } else if  String(format: "%02X", data![0]) == "02"&&String(format: "%02X", data![1]) == "30" { // 接收机参数设置成功
                print("接收机参数设置成功")
                if currentClickType == 6 { // 显示器参数设置成功
                    setToucheMac()
                }
            } else if  String(format: "%02X", data![0]) == "02"&&String(format: "%02X", data![1]) == "31" { // 接收机参数设置失败
                print("接收机参数设置失败")
                self.view.makeToast("接收机参数设置失败", duration: 3.0, position: .center)
            } else if  String(format: "%02X", data![0]) == "0C" { // 接收到挂车数量
                print("接收到挂车数量")
                settingNumberOfTraler(data)
            } else if  String(format: "%02X", data![0]) == "0D" { // 接收到挂车mac
                print("接收到挂车id")
                if currentClickType == 6 { // 显示器获取头车ID
                    getToucheMACAddress(data, true)
                } else { // 接收机获取挂车MAC
                    trailerMACInit(data, 2)
                }
                
            } else if  String(format: "%02X", data![0]) == "03"&&String(format: "%02X", data![1]) == "47" { // 挂车mac为空
                if currentClickType == 6 { // 显示器获取头车ID
                    getToucheMACAddress(data, false)
                } else { // 接收机获取挂车MAC
                    trailerMACInit(data, 3)
                }
            } else if  String(format: "%02X", data![0]) == "02"&&String(format: "%02X", data![1]) == "44" { // 挂车mac设置成功
                if currentClickType == 6 { //  显示器
                    print("设置成功")
                    setDisplaySuccess()
                } else { // 接收机
                    judgeUpAndDown() // 判断是否全部设置成功
                }
                print("挂车mac设置成功")
            } else if  String(format: "%02X", data![0]) == "03"&&String(format: "%02X", data![1]) == "44" {
               // self.view.makeToast("设置失败", duration: 3.0, position: .center)
                print("设置失败")
            } else if  String(format: "%02X", data![0]) == "02"&&String(format: "%02X", data![1]) == "45" { // 擦除挂车成功
                if currentClickType == 6 { //  显示器
                    setDisplaySuccess()
                    print("设置成功")
                } else { // 接收机
                    judgeUpAndDown() // 判断是否全部设置成功
                }
                print("擦除挂车成功")
            } else if  String(format: "%02X", data![0]) == "03"&&String(format: "%02X", data![1]) == "45" {
               // self.view.makeToast("设置失败", duration: 3.0, position: .center)
                print("设置失败")
            } else if  String(format: "%02X", data![0]) == "02"&&String(format: "%02X", data![1]) == "42" { // 挂车数量设置成功
                print("挂车数量设置成功")
            } else if  String(format: "%02X", data![0]) == "0A" { // 获取轮胎位号
                print("收到轮胎位号")
                if currentClickType == 2 {
                    tyrePositionInit(data)
                } else if currentClickType == 3 {
                    getAllTyrePosition(data) // 获取所有已绑定的轮胎位号
                }
            } else if  String(format: "%02X", data![0]) == "07" { // 获取轮胎参数
                print("收到轮胎参数")
                if getTyreTpmsClickType == 1 {
                    goTyreThresholdSettingView(data)
                } else if  getTyreTpmsClickType == 2 {
                    goWheelSensorView(data)
                } else if getTyreTpmsClickType == 3 {
                    getAllThresholeSettingArray(data)
                } else if getTyreTpmsClickType == 4 {
                    goWheelSensorViewNoBind(data)
                }
            } else if  String(format: "%02X", data![0]) == "02"&&String(format: "%02X", data![1]) == "3E" { // 阈值设置成功
                print("阈值设置成功")
                refreshAllBindTyreThreshold() // 刷新所有已绑定的轮胎阈值
            } else if  String(format: "%02X", data![0]) == "02"&&String(format: "%02X", data![1]) == "3F" { // 轮胎擦除成功
                print("轮胎擦除成功")
                returnTyreViewController(1)
            }  else if  String(format: "%02X", data![0]) == "02"&&String(format: "%02X", data![1]) == "37" { // 轮胎传感器设置成功
                print("轮胎传感器设置成功")
                if getTyreTpmsClickType == 3 {
                    setTyreThresholeFun()
                } else {
                    returnTyreViewController(2)
                }
                
            } else if  String(format: "%02X", data![0]) == "0F" { // 轮胎数据
                print("轮胎数据获取成功")
                goTyreDisplay(data)
            } else if  String(format: "%02X", data![0]) == "06" { // 查询ID(查版本）
                print("版本号获取成功")
                goUpgradeView(data)
            } else if  String(format: "%02X", data![0]) == "01"&&String(format: "%02X", data![1]) == "00"&&String(format: "%02X", data![6]) == "01" { // 收到固件升级第一步——配置版本号返回数据
                firmwareUpgradeSave2()
            } else if  String(format: "%02X", data![0]) == "01"&&String(format: "%02X", data![1]) == "02"&&String(format: "%02X", data![6]) == "01" { // 收到固件升级第二步——发送开始返回数据
                firmwareUpgradeSave3()
            } else if  String(format: "%02X", data![0]) == "01"&&String(format: "%02X", data![1]) == "03" { // 收到固件升级第四步——发送结束返回数据
                firmwareUpgradeSave5()
            } else if  String(format: "%02X", data![0]) == "01"&&String(format: "%02X", data![1]) == "04" { // 收到固件升级第五步——发送校验返回数据
                firmwareUpgradeSave6()
            }
        }
    }
    
    /** 写入数据 */
    func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
        print("写入数据")
        print(error)
    }
    
    /** 诊断数据赋值 */
    func deviceInit(_ data: Data?) {
        let vc = HamatonDiagnoseViewController()
        vc.deviceData.changgui = ChangguiCapitals[String(format: "%02X", data![1])] ?? "未知"
        vc.deviceData.changguiNum = String(data![2])
        vc.deviceData.CAN = CANCapitals[String(format: "%02X", data![3])] ?? "未知"
        vc.deviceData.CANNum = String(data![4])
        vc.deviceData.RFXinpian = RFXinpianCapitals[String(format: "%02X", data![5])] ?? "未知"
        vc.deviceData.RFXinpianNum = String(data![6])
        vc.deviceData.UART = UARTCapitals[String(format: "%02X", data![7])] ?? "未知"
        vc.deviceData.UARTNum = String(data![8])
        vc.deviceData.CANXinpian = CANXinpianCapitals[String(format: "%02X", data![9])] ?? "未知"
        vc.deviceData.CANXinpianNum = String(data![10])
        vc.deviceData.LPW = CANXinpianCapitals[String(format: "%02X", data![11])] ?? "未知"
        vc.deviceData.LPWNum = String(data![12])
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: false)
    }
    // ACSII转为十六进制
    func hexStringToBytes(_ hexString: String) -> [UInt8]? {
        // 去除字符串中的空格
        let hexStringCleaned = hexString.replacingOccurrences(of: " ", with: "")
        
        // 检查字符串长度是否为偶数
        guard hexStringCleaned.count % 2 == 0 else {
            return nil // 长度不是偶数，无法将其解析为字节
        }
        
        var bytes = [UInt8]()
        var index = hexStringCleaned.startIndex
        
        // 遍历字符串中的每一对字符
        while index < hexStringCleaned.endIndex {
            let nextIndex = hexStringCleaned.index(index, offsetBy: 2)
            if let byte = UInt8(hexStringCleaned[index..<nextIndex], radix: 16) {
                bytes.append(byte)
            } else {
                return nil // 无法将字符串解析为十六进制数值
            }
            index = nextIndex
        }
        
        return bytes
    }
    
    // 蓝牙名称转十六进制并去除开头的额外05
    func removeExtra05FromHexString(_ hexString: String) -> String {
        // 找到第一个非 05 字符的位置
        guard let firstNon05Index = hexString.firstIndex(where: { $0 != "0" && $0 != "5" }) else {
            // 如果全部字符都是 05，则返回空字符串
            return ""
        }
        // 截取从第一个非 05 字符开始到末尾的子字符串
        let trimmedHexString = String(hexString[firstNon05Index...])
        
        return trimmedHexString
    }
    
    /**设备名称赋值**/
    func equipmentNameInit(_ data: Data?) {
        // 将 Data 转换为十六进制的 ASCII 码数组
        let byteArray = [UInt8](data!)
        // 将十六进制的 ASCII 码数组转换为字符串
        let convertedString = String(bytes: byteArray, encoding: .ascii)
        // 将字符串转为数组
        let nameArr = convertedString!.components(separatedBy: " ")
        equipmentName_prefix = nameArr[0] // 蓝牙名称前缀赋值
        // 弹框
        let message = "\n自动设置固定头部：" + equipmentName_prefix
        let alertController = UIAlertController(title: "修改蓝牙设备名称", message: "", preferredStyle: .alert)
        let inputAction = UIAlertAction(title: "设备名称", style: .default) { (action) in
            
        }
        let cancelAction = UIAlertAction(title: NSLocalizedString("取消", tableName: "HamatonLocalizable", comment: ""), style: .cancel, handler: nil)
        let saveAction = UIAlertAction(title: "修改", style: .default) { action in
            if let deviceName = alertController.textFields?.first?.text! {
                // 拼接字符串
                let newDeviceName = equipmentName_prefix + " " + deviceName
                var hexString = "31" + self.removeExtra05FromHexString(newDeviceName.utf8.map { String(format: "%02X", $0) }.joined())
                let byte = self.hexStringToBytes(hexString)!
                let data = Data(bytes: byte, count: byte.count)
                
                // 写入蓝牙名称
                self.connectedPeripheral!.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)

            }
        }
        // 设置message
        let attributedMessage = NSMutableAttributedString(string: message)
        // 设置消息文本的样式
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = .left // 设置文字对齐方式为左对齐
        attributedMessage.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attributedMessage.length))
        attributedMessage.addAttribute(.font, value: UIFont.boldSystemFont(ofSize: 14), range: NSRange(location: 0, length: attributedMessage.length))
        attributedMessage.addAttribute(.foregroundColor, value: UIColor.gray, range: NSRange(location: 0, length: attributedMessage.length))
        
        alertController.addAction(cancelAction)
        alertController.addAction(saveAction)
        alertController.setValue(attributedMessage, forKey: "attributedMessage")
        alertController.addTextField{ (textField) in
            //在闭包中可以对UITextField进行配置
            textField.placeholder = "请输入新的蓝牙名称"
        }
        self.present(alertController, animated: true, completion: nil)
         
    }
    
    /**设备配置参数赋值**/
    func equipmentConfigInit(_ data: Data?, _ numData: Data?) {
        let id1 = String(format: "%02X", data![1])
        let id5 = String(format: "%02X", data![5])
        let id7 = String(format: "%02X", data![7])
        let id8 = String(format: "%02X", data![8])
        let id10 = String(format: "%02X", data![10])
        let id12 = String(format: "%02X", data![12])
        let id13 = String(format: "%02X", data![13])
        let id14 = String(format: "%02X", data![14])
        let id1414 = Int(id14 ?? "1", radix: 16)
        let num = String(numData![1])
        trailerNumber = num
        var deviceModelInitData = DeviceSettingCellModel(carTypeModel: HamatonCarModel(id: id5, name: CarTypeOption[id5]!),
                                                         communicationTypeModel: HamatonCarModel(id: id1, name: CommunicationTypeOption[id1]!),
                                                         CANCommunicationBaudRateModel: HamatonCarModel(id: id12, name: CANCommunicationBaudRateOption[id12]!),
                                                         CANTerminalResistanceModel: id13 == "00" ? "ON" : "OFF",
                                                         CANMailingAddressModel: HamatonCarModel(id: String(id1414 ?? 1), name: String(id1414 ?? 1)), // 十六进制转为十进制
                                                         PCTRFChannel1Model: HamatonCarModel(id: id7, name: PCTRFChannel1Option[id7]!),
                                                         PCTRFChannel2Model: HamatonCarModel(id: id8, name: PCTRFChannel2Option[id8]!),
                                                         temperatureCompensationModel: id10 == "00" ? "OFF" : "ON",
                                                         NumberOfTrailersModel: HamatonCarModel(id: num, name: num)
        )
        let vc = HamatonCarSettingViewController(deviceModel: deviceModelInitData)
        vc.hidesBottomBarWhenPushed = true
        vc.delegate = self
        self.navigationController?.pushViewController(vc, animated: false)
    }
    
    // 设置挂车数量
    func settingNumberOfTraler(_ data: Data?) {
        equipmentConfigInit(equipmentData, data)
    }
    
    // 挂车参数初始化
    func trailerMACInit(_ data: Data?, _ type: Int) { // type: 2 挂车有mac type: 3 挂车无mac
        print("输出挂车Mac")
        if (type == 2) {
            let mac1 = String(format: "%02X", data![1])
            let mac2 = String(format: "%02X", data![2])
            let mac3 = String(format: "%02X", data![3])
            let mac4 = String(format: "%02X", data![4])
            let mac5 = String(format: "%02X", data![5])
            let mac6 = String(format: "%02X", data![6])
            
            if (data![7] == 1) {
                tnModel.macAddress1 = mac1 + ":" + mac2 + ":" + mac3 + ":" + mac4 + ":" + mac5 + ":" + mac6
            } else if (data![7] == 2) {
                tnModel.macAddress2 = mac1 + ":" + mac2 + ":" + mac3 + ":" + mac4 + ":" + mac5 + ":" + mac6
            } else if (data![7] == 3) {
                tnModel.macAddress3 = mac1 + ":" + mac2 + ":" + mac3 + ":" + mac4 + ":" + mac5 + ":" + mac6
            } else if (data![7] == 4) {
                tnModel.macAddress4 = mac1 + ":" + mac2 + ":" + mac3 + ":" + mac4 + ":" + mac5 + ":" + mac6
            } else if (data![7] == 5) {
                tnModel.macAddress5 = mac1 + ":" + mac2 + ":" + mac3 + ":" + mac4 + ":" + mac5 + ":" + mac6
            } else if (data![7] == 6) {
                tnModel.macAddress6 = mac1 + ":" + mac2 + ":" + mac3 + ":" + mac4 + ":" + mac5 + ":" + mac6
            }
            if trailerNumber == String(data![7]) {
                let vc = HamatonUpAndDownViewController()
                vc.trailersNumOption = tnModel
                vc.trailerNum = trailerNumber
                vc.delegate = self
                navigationController?.pushViewController(vc, animated: false)
            }
        } else {
            if (currentTrailer == 1) {
                tnModel.macAddress1 = ""
            } else if (currentTrailer == 2) {
                tnModel.macAddress2 = ""
            } else if (currentTrailer == 3) {
                tnModel.macAddress3 = ""
            } else if (currentTrailer == 4) {
                tnModel.macAddress4 = ""
            } else if (currentTrailer == 5) {
                tnModel.macAddress5 = ""
            } else if (currentTrailer == 6) {
                tnModel.macAddress6 = ""
            }
            if trailerNumber == String(currentTrailer) {
                let vc = HamatonUpAndDownViewController()
                vc.trailersNumOption = tnModel
                vc.trailerNum = trailerNumber
                vc.delegate = self
                navigationController?.pushViewController(vc, animated: false)
            }
        }
        
        currentTrailer = currentTrailer + 1
        
        
    }
    
    // 写入接收机设置
    func saveDeviceSetting(_ hexString: String) {
        // 在这里执行委托方法的具体实现
        let byte = self.hexStringToBytes(hexString)!
        let data = Data(bytes: byte, count: byte.count)
        self.connectedPeripheral!.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
    }
    
    // 保存挂车数量
    func saveTrailerNum(_ hexString: String, _ carNum: String) {
        // 在这里执行委托方法的具体实现
        let byte = self.hexStringToBytes(hexString)!
        let data = Data(bytes: byte, count: byte.count)
        trailerNumber = carNum
        self.connectedPeripheral!.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
    }
    
    // 上下挂设置保存
    func didUpAndDownSave(_ trailersNumOption: trailerNumModel) {
        // hamatonCarSettingViewSaveClick() // 设置保存的时候要不要同时保存其他参数
        // 创建一个 DispatchQueue 用于执行循环任务
        let dispatchQueue = DispatchQueue.global()
        let dataToSend = ["4401", "4402", "4403", "4404", "4405", "4406"] // 设置mac
        let dataToSendCErase = ["4501", "4502", "4503", "4504", "4505", "4506"] // 擦除mac
        currentTrailer = 1
        let tnum = Int(trailerNumber)!
        for (index, item) in dataToSend.enumerated() {
            // 在每次循环之前等待 300 毫秒
            let delayTime = DispatchTime.now() + .milliseconds(index * 300)
            dispatchQueue.asyncAfter(deadline: delayTime) {
                if (index < tnum) {
                    var hexString = String(item)
                    if (index == 0) {
                        // mac输入框有值就传dataToSend进行设置，没有值就传dataToSendCErase进行擦除
                        hexString = trailersNumOption.macAddress1 == "" ? dataToSendCErase[index] : dataToSend[index]
                        hexString = hexString + trailersNumOption.macAddress1.replacingOccurrences(of: ":", with: "")
                    } else if index == 1 {
                        // mac输入框有值就传dataToSend进行设置，没有值就传dataToSendCErase进行擦除
                        hexString = trailersNumOption.macAddress2 == "" ? dataToSendCErase[index] : dataToSend[index]
                        hexString = hexString + trailersNumOption.macAddress2.replacingOccurrences(of: ":", with: "")
                    } else if index == 2 {
                        // mac输入框有值就传dataToSend进行设置，没有值就传dataToSendCErase进行擦除
                        hexString = trailersNumOption.macAddress3 == "" ? dataToSendCErase[index] : dataToSend[index]
                        hexString = hexString + trailersNumOption.macAddress3.replacingOccurrences(of: ":", with: "")
                    } else if index == 3 {
                        // mac输入框有值就传dataToSend进行设置，没有值就传dataToSendCErase进行擦除
                        hexString = trailersNumOption.macAddress4 == "" ? dataToSendCErase[index] : dataToSend[index]
                        hexString = hexString + trailersNumOption.macAddress4.replacingOccurrences(of: ":", with: "")
                    } else if index == 4 {
                        // mac输入框有值就传dataToSend进行设置，没有值就传dataToSendCErase进行擦除
                        hexString = trailersNumOption.macAddress5 == "" ? dataToSendCErase[index] : dataToSend[index]
                        hexString = hexString + trailersNumOption.macAddress5.replacingOccurrences(of: ":", with: "")
                    } else if index == 5 {
                        // mac输入框有值就传dataToSend进行设置，没有值就传dataToSendCErase进行擦除
                        hexString = trailersNumOption.macAddress6 == "" ? dataToSendCErase[index] : dataToSend[index]
                        hexString = hexString + trailersNumOption.macAddress6.replacingOccurrences(of: ":", with: "")
                    }
                    let byte = self.hexStringToBytes(hexString)!
                    let data = Data(bytes: byte, count: byte.count)
                    self.connectedPeripheral!.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
                } else {
                    self.currentTrailer = 1 // 请求成功后当前挂车重新设置为1，方便后边判断挂车mac是否设置成功
                }
            }
        }
    }
    // 跳转到上下挂设置页
    func navigateToViewController3() {
        // 创建一个 DispatchQueue 用于执行循环任务
        let dispatchQueue = DispatchQueue.global()
        // searchCarIdType = 1
        let dataToSend = ["4701", "4702", "4703", "4704", "4705", "4706"]
        currentTrailer = 1
        let tnum = Int(trailerNumber)!
        for (index, item) in dataToSend.enumerated() {
            // 在每次循环之前等待 300 毫秒
            let delayTime = DispatchTime.now() + .milliseconds(index * 300)
            dispatchQueue.asyncAfter(deadline: delayTime) {
                if (index < tnum) {
                    let hexString = String(item)
                    let byte = self.hexStringToBytes(hexString)!
                    let data = Data(bytes: byte, count: byte.count)
                    self.connectedPeripheral!.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
                }
            }
        }
    }
    // 判断挂车MAC是否全部设置成功
    func judgeUpAndDown() {
        let tnum = Int(trailerNumber)!
        if currentTrailer == tnum {
            // 获取上一页面的视图控制器
            if let previousVC = navigationController?.viewControllers.last as? HamatonUpAndDownViewController {
                // 调用上一页面的刷新数据方法
                previousVC.macSettingSuccess()
            }
            // 返回上一页面
            navigationController?.popViewController(animated: false)
        } else {
            currentTrailer = currentTrailer + 1
        }
    }
    // 初始化轮胎位号
    func tyrePositionInit(_ data: Data?) {
        carTyreModel.tyre16 = false
        carTyreModel.tyre17 = false
        carTyreModel.tyre19 = false
        carTyreModel.tyre1a = false
        carTyreModel.tyre26 = false
        carTyreModel.tyre27 = false
        carTyreModel.tyre29 = false
        carTyreModel.tyre2a = false
        carTyreModel.tyre36 = false
        carTyreModel.tyre37 = false
        carTyreModel.tyre39 = false
        carTyreModel.tyre3a = false
        carTyreModel.tyre46 = false
        carTyreModel.tyre47 = false
        carTyreModel.tyre49 = false
        carTyreModel.tyre4a = false
        let count = Int(data?.count ?? 1)
        carTyreBindNum = count - 1
        for index in 1..<count {
            let item = String(format: "%02X", data![index]) ?? ""
            switch item {
            case "16" :
                carTyreModel.tyre16 = true
            case "17" :
                carTyreModel.tyre17 = true
            case "19" :
                carTyreModel.tyre19 = true
            case "1A" :
                carTyreModel.tyre1a = true
            case "26" :
                carTyreModel.tyre26 = true
            case "27" :
                carTyreModel.tyre27 = true
            case "29" :
                carTyreModel.tyre29 = true
            case "2A" :
                carTyreModel.tyre2a = true
            case "36" :
                carTyreModel.tyre36 = true
            case "37" :
                carTyreModel.tyre37 = true
            case "39" :
                carTyreModel.tyre39 = true
            case "3A" :
                carTyreModel.tyre3a = true
            case "46" :
                carTyreModel.tyre46 = true
            case "47" :
                carTyreModel.tyre47 = true
            case "49" :
                carTyreModel.tyre49 = true
            case "4A" :
                carTyreModel.tyre4a = true
            default:
                //fatalError("Encountered an unknown carTyre")
                print("有无法识别的carTyre")
                break
            }
        }
        let vc = HamatonCarTyreViewController()
        vc.hidesBottomBarWhenPushed = true
        vc.carType = String(equipmentData![5])
        vc.carTyreModel = carTyreModel
        // vc.delegate = self
        self.navigationController?.pushViewController(vc, animated: false)
    }
    // 跳转到阈值设置
    func navigateToThresholdSettingView() {
        print("跳转到阈值设置")
        getTyreTpmsClickType = 1
        if carTyreBindNum > 0 {
            if carTyreModel.tyre16 == true {
                getTyreArgument("3816")
            } else if carTyreModel.tyre17 == true {
                getTyreArgument("3817")
            } else if carTyreModel.tyre19 == true {
                getTyreArgument("3819")
            } else if carTyreModel.tyre1a == true {
                getTyreArgument("381A")
            } else if carTyreModel.tyre26 == true {
                getTyreArgument("3826")
            } else if carTyreModel.tyre27 == true {
                getTyreArgument("3827")
            } else if carTyreModel.tyre29 == true {
                getTyreArgument("3829")
            } else if carTyreModel.tyre2a == true {
                getTyreArgument("382A")
            } else if carTyreModel.tyre36 == true {
                getTyreArgument("3836")
            } else if carTyreModel.tyre37 == true {
                getTyreArgument("3837")
            } else if carTyreModel.tyre39 == true {
                getTyreArgument("3839")
            } else if carTyreModel.tyre3a == true {
                getTyreArgument("383A")
            } else if carTyreModel.tyre46 == true {
                getTyreArgument("3846")
            } else if carTyreModel.tyre47 == true {
                getTyreArgument("3847")
            } else if carTyreModel.tyre49 == true {
                getTyreArgument("3849")
            } else if carTyreModel.tyre4a == true {
                getTyreArgument("384A")
            } else {
                let vc = HamatonThresholdSettingViewController()
                vc.hidesBottomBarWhenPushed = true
                vc.delegate = self
                self.navigationController?.pushViewController(vc, animated: false)
            }
        }
    }
    // 获取轮胎参数
    func getTyreArgument(_ str: String) {
        let hexString = String(str)
        let byte = self.hexStringToBytes(hexString)!
        let data = Data(bytes: byte, count: byte.count)
        self.connectedPeripheral!.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
    }
    // 获取轮胎参数后跳转到阈值设置
    func goTyreThresholdSettingView(_ data: Data?) {
        let diya = Int(String(format: "%02X", data![8]) + String(format: "%02X", data![7]), radix: 16)
        let jidiya = Int(String(format: "%02X", data![10]) + String(format: "%02X", data![9]), radix: 16)
        let gaoya = Int(String(format: "%02X", data![12]) + String(format: "%02X", data![11]), radix: 16)
        var gaowenNum = 0
        if let gwNum = Int(String(format: "%02X", data![13]), radix: 16) {
            if (gwNum > 0) {
                gaowenNum = gwNum - 40
            }
        }
        let gaowen = gaowenNum
        //let gaowen = Int(String(format: "%02X", data![13]), radix: 16)
        let shijian = Int(String(format: "%02X", data![14]), radix: 16)
        let vc = HamatonThresholdSettingViewController()
        vc.hidesBottomBarWhenPushed = true
        vc.delegate = self
        vc.thresholdSettingModel.diyaStr = String(diya!)
        vc.thresholdSettingModel.zuidiyaStr = String(jidiya!)
        vc.thresholdSettingModel.gaoyaStr = String(gaoya!)
        vc.thresholdSettingModel.gaowenStr = String(gaowen)
        vc.thresholdSettingModel.shijianStr = String(shijian!)
        self.navigationController?.pushViewController(vc, animated: false)
    }
    // 字符串前两位与后两位位置对调
    func swapFirstAndLastTwo(_ str: String) -> String {
        // 确保字符串长度至少为 2，否则不需要交换
        guard str.count >= 2 else {
            return str
        }
        // 将字符串拆分为前两位和后面的部分
        let startIndex = str.startIndex
        let endIndex = str.index(startIndex, offsetBy: 2)
        let firstTwo = str[startIndex..<endIndex]
        let remaining = str[endIndex...]
        
        // 将前两位和后两位交换位置后拼接起来
        return "\(remaining)\(firstTwo)"
    }
    // 阈值设置保存
    func saveThresholdSetting(_ thresholdSettingModel: ThresholdSettingModel) {
        print("阈值设置保存")
        print(thresholdSettingModel)
        var hexString = "3E"
        let diyaNum = Int(thresholdSettingModel.diyaStr) ?? 0
        let diyaPour = swapFirstAndLastTwo(String(format: "%04X", diyaNum)) // 转为十六进制并调换位置
        let zuidiyaNum = Int(thresholdSettingModel.zuidiyaStr) ?? 0
        let zuidiyaPour = swapFirstAndLastTwo(String(format: "%04X", zuidiyaNum))
        let gaoyaNum = Int(thresholdSettingModel.gaoyaStr) ?? 0
        let gaoyaPour = swapFirstAndLastTwo(String(format: "%04X", gaoyaNum))
        var gaowenNum = 0
        if let gwNum = Int(thresholdSettingModel.gaowenStr) {
            if (gwNum > 0) {
                gaowenNum = gwNum + 40
            }
        }
        let gaowen = String(format: "%02X", Int(gaowenNum))
        let shijian = String(format: "%02X", Int(thresholdSettingModel.shijianStr) ?? 0)
        hexString = hexString + diyaPour + zuidiyaPour + gaoyaPour + gaowen + shijian + "192A3200050020000602"
        thresholdSettingStr = diyaPour + zuidiyaPour + gaoyaPour + gaowen + shijian // 保存为整车阈值，为后边每个轮位的更新做准备
        let byte = self.hexStringToBytes(hexString)!
        let data = Data(bytes: byte, count: byte.count)
        self.connectedPeripheral!.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
    }
    // 跳转到轮胎设置
    func navigateToWheelSensorView(_ str: String, _ bool: Bool) {
        let hexString = "38" + str
        if bool {
            // 已绑定
            getTyreTpmsClickType = 2
            let byte = self.hexStringToBytes(hexString)!
            let data = Data(bytes: byte, count: byte.count)
            self.connectedPeripheral!.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
        } else {
            // 未绑定
            getTyreTpmsClickType = 4
            currentClickTyreStr = str
            goWheelSensorViewBefore()
        }
    }
    // 跳转到已绑定轮胎设置页面
    func goWheelSensorView(_ data: Data?) {
        let luntaiweizhi = String(format: "%02X", data![6])
        let chuanganqiType = Int(String(format: "%02X", data![5]), radix: 16)
        let chuanganqiId = String(format: "%02X", data![1]) + String(format: "%02X", data![2]) + String(format: "%02X", data![3]) + String(format: "%02X", data![4])
        let diya = Int(String(format: "%02X", data![8]) + String(format: "%02X", data![7]), radix: 16)
        let jidiya = Int(String(format: "%02X", data![10]) + String(format: "%02X", data![9]), radix: 16)
        let gaoya = Int(String(format: "%02X", data![12]) + String(format: "%02X", data![11]), radix: 16)
        var gaowenNum = 0
        if let gwNum = Int(String(format: "%02X", data![13]), radix: 16) {
            if (gwNum > 0) {
                gaowenNum = gwNum - 40
            }
        }
        let gaowen = gaowenNum
        // let gaowen = Int(String(format: "%02X", data![13]), radix: 16)
        let shijian = Int(String(format: "%02X", data![14]), radix: 16)
        let vc = HamatonWheelSensorViewController()
        vc.hidesBottomBarWhenPushed = true
        vc.delegate = self
        vc.isBind = true
        vc.tyreSettingModel.luntaiweizhiStr = luntaiweizhi
        vc.tyreSettingModel.chuanganqiTypeId = String(chuanganqiType!)
        vc.tyreSettingModel.chuanganqiIDStr = chuanganqiId
        vc.tyreSettingModel.diyaStr = String(diya!)
        vc.tyreSettingModel.zuidiyaStr = String(jidiya!)
        vc.tyreSettingModel.gaoyaStr = String(gaoya!)
        vc.tyreSettingModel.gaowenStr = String(gaowen)
        vc.tyreSettingModel.shijianStr = String(shijian!)
        self.navigationController?.pushViewController(vc, animated: false)
    }
    // 跳转到未绑定轮胎设置页面之前要先获取整车轮胎阈值
    func goWheelSensorViewBefore() {
        print("跳转到未绑定轮胎设置页面之前要先获取整车轮胎阈值")
        // getTyreTpmsClickType = 4
        if carTyreBindNum > 0 {
            if carTyreModel.tyre16 == true {
                getTyreArgument("3816")
            } else if carTyreModel.tyre17 == true {
                getTyreArgument("3817")
            } else if carTyreModel.tyre19 == true {
                getTyreArgument("3819")
            } else if carTyreModel.tyre1a == true {
                getTyreArgument("381A")
            } else if carTyreModel.tyre26 == true {
                getTyreArgument("3826")
            } else if carTyreModel.tyre27 == true {
                getTyreArgument("3827")
            } else if carTyreModel.tyre29 == true {
                getTyreArgument("3829")
            } else if carTyreModel.tyre2a == true {
                getTyreArgument("382A")
            } else if carTyreModel.tyre36 == true {
                getTyreArgument("3836")
            } else if carTyreModel.tyre37 == true {
                getTyreArgument("3837")
            } else if carTyreModel.tyre39 == true {
                getTyreArgument("3839")
            } else if carTyreModel.tyre3a == true {
                getTyreArgument("383A")
            } else if carTyreModel.tyre46 == true {
                getTyreArgument("3846")
            } else if carTyreModel.tyre47 == true {
                getTyreArgument("3847")
            } else if carTyreModel.tyre49 == true {
                getTyreArgument("3849")
            } else if carTyreModel.tyre4a == true {
                getTyreArgument("384A")
            } else {
                let vc = HamatonWheelSensorViewController()
                vc.hidesBottomBarWhenPushed = true
                vc.canEditThreshold = true
                vc.isBind = false
                vc.delegate = self
                self.navigationController?.pushViewController(vc, animated: false)
            }
        }
    }
    // 跳转到未绑定轮胎的设置页面
    func goWheelSensorViewNoBind(_ data: Data?) {
        let luntaiweizhi = currentClickTyreStr
        let diya = Int(String(format: "%02X", data![8]) + String(format: "%02X", data![7]), radix: 16)
        let jidiya = Int(String(format: "%02X", data![10]) + String(format: "%02X", data![9]), radix: 16)
        let gaoya = Int(String(format: "%02X", data![12]) + String(format: "%02X", data![11]), radix: 16)
        var gaowenNum = 0
        if let gwNum = Int(String(format: "%02X", data![13]), radix: 16) {
            if (gwNum>0) {
                gaowenNum = gwNum - 40
            }
        }
        let gaowen = gaowenNum
        // let gaowen = Int(String(format: "%02X", data![13]), radix: 16)
        let shijian = Int(String(format: "%02X", data![14]), radix: 16)
        let vc = HamatonWheelSensorViewController()
        vc.hidesBottomBarWhenPushed = true
        vc.canEditThreshold = false // 后期要单个设置可以放开
        vc.isBind = false
        vc.delegate = self
        vc.tyreSettingModel.luntaiweizhiStr = luntaiweizhi
        vc.tyreSettingModel.diyaStr = String(diya!)
        vc.tyreSettingModel.zuidiyaStr = String(jidiya!)
        vc.tyreSettingModel.gaoyaStr = String(gaoya!)
        vc.tyreSettingModel.gaowenStr = String(gaowen)
        vc.tyreSettingModel.shijianStr = String(shijian!)
        self.navigationController?.pushViewController(vc, animated: false)
    }
    // MARK: 十进制 -> 两位十六进制
    func decimalToHexadecimal2(_ str: String) -> String {
        if let str0 = Int(str) {
            return String(format: "%02X", str0)
        } else {
            return "00"
        }
    }
    // MARK: 十进制 -> 四位十六进制
    func decimalToHexadecimal4(_ str: String) -> String {
        if let str0 = Int(str) {
            return String(format: "%04X", str0)
        } else {
            return "0000"
        }
    }
    // 保存轮胎传感器设置
    func saveWheelSensor(_ tyreSettingModel: TyreSettingModel) {
        print("保存轮胎传感器啦")
        var hexString = "37"
        let chuanganqiTypeId = CgqTypeOption2[tyreSettingModel.chuanganqiTypeId]
        let chuanganqiId = tyreSettingModel.chuanganqiIDStr
        let luntaiweizhi = tyreSettingModel.luntaiweizhiStr
        let diya = tyreSettingModel.diyaStr
        let diyaStr = swapFirstAndLastTwo(decimalToHexadecimal4(diya))
        let zuidiya = tyreSettingModel.zuidiyaStr
        let zuidiyaStr = swapFirstAndLastTwo(decimalToHexadecimal4(zuidiya))
        let gaoya = tyreSettingModel.gaoyaStr
        let gaoyaStr = swapFirstAndLastTwo(decimalToHexadecimal4(gaoya))
        var gaowenNum = 0
        if let gwNum = Int(tyreSettingModel.gaowenStr) {
            if (gwNum>0) {
                gaowenNum = gwNum + 40
            }
        }
        let gaowen = decimalToHexadecimal2(String(gaowenNum))
        //let gaowen = decimalToHexadecimal2(tyreSettingModel.gaowenStr)
        let shijian = decimalToHexadecimal2(tyreSettingModel.shijianStr)
        let otherStr = "192A3200050020000602"
        let hexString1 = chuanganqiId + chuanganqiTypeId! + luntaiweizhi
        let hexString2 = diyaStr + zuidiyaStr + gaoyaStr
        let hexString3 = gaowen + shijian + otherStr
        hexString = hexString + hexString1 + hexString2 + hexString3
        let byte = self.hexStringToBytes(hexString)!
        let data = Data(bytes: byte, count: byte.count)
        self.connectedPeripheral!.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
        
    }
    // 擦除某个轮胎
    func cancelWheelSensor(_ tyreSettingModel: TyreSettingModel) {
        print("擦除轮胎啦")
        currentTyreStr = tyreSettingModel.luntaiweizhiStr
        let hexString = "3F" + tyreSettingModel.luntaiweizhiStr
        let byte = self.hexStringToBytes(hexString)!
        let data = Data(bytes: byte, count: byte.count)
        self.connectedPeripheral!.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
    }
    // 从传感器设置页面返回轮胎参数页面 1 擦除 2 设置
    func returnTyreViewController(_ type: Int) {
        // 获取上一页面的视图控制器
        if let previousVC = navigationController?.viewControllers[1] as? HamatonCarTyreViewController {
            // 调用上一页面的刷新数据方法
            previousVC.refreshData(currentTyreStr, type)
        }
        // 返回上一页面
        navigationController?.popViewController(animated: false)
    }
    // 刷新所有已绑定的轮胎阈值
    func refreshAllBindTyreThreshold() {
        getTyreTpmsClickType = 3
        allThresholeSettingArray = []
        bindList = []
        getThresholeSettingNum = 0
        setTyreThresholeNum = 0
        if carTyreModel.tyre16 == true {
            bindList.append("16")
        }
        if carTyreModel.tyre17 == true {
            bindList.append("17")
        }
        if carTyreModel.tyre19 == true {
            bindList.append("19")
        }
        if carTyreModel.tyre1a == true {
            bindList.append("1A")
        }
        if carTyreModel.tyre26 == true {
            bindList.append("26")
        }
        if carTyreModel.tyre27 == true {
            bindList.append("27")
        }
        if carTyreModel.tyre29 == true {
            bindList.append("29")
        }
        if carTyreModel.tyre2a == true {
            bindList.append("2A")
        }
        if carTyreModel.tyre36 == true {
            bindList.append("36")
        }
        if carTyreModel.tyre37 == true {
            bindList.append("37")
        }
        if carTyreModel.tyre39 == true {
            bindList.append("39")
        }
        if carTyreModel.tyre3a == true {
            bindList.append("3A")
        }
        if carTyreModel.tyre46 == true {
            bindList.append("46")
        }
        if carTyreModel.tyre47 == true {
            bindList.append("47")
        }
        if carTyreModel.tyre49 == true {
            bindList.append("49")
        }
        if carTyreModel.tyre4a == true {
            bindList.append("4A")
        }
        let dispatchQueue = DispatchQueue.global()
        for (index, item) in bindList.enumerated() {
            // 在每次循环之前等待 300 毫秒
            let delayTime = DispatchTime.now() + .milliseconds(index * 300)
            dispatchQueue.asyncAfter(deadline: delayTime) {
                let hexString = "38" + String(item)
                let byte = self.hexStringToBytes(hexString)!
                let data = Data(bytes: byte, count: byte.count)
                self.connectedPeripheral!.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
            }
        }
    }
    // 获取所有已绑定的轮胎参数
    func getAllThresholeSettingArray(_ data: Data?) {
        let luntaiweizhi = String(format: "%02X", data![6])
        let chuanganqiType = String(format: "%02X", data![5])
        let chuanganqiId = String(format: "%02X", data![1]) + String(format: "%02X", data![2]) + String(format: "%02X", data![3]) + String(format: "%02X", data![4])
        let hexString1 = "37" + chuanganqiId + chuanganqiType + luntaiweizhi
        let hexString = hexString1 + thresholdSettingStr + "192A3200050020000602"
        allThresholeSettingArray.append(hexString)
        getThresholeSettingNum = getThresholeSettingNum + 1
        if getThresholeSettingNum == bindList.count {
            let dispatchQueue = DispatchQueue.global()
            for (index, item) in allThresholeSettingArray.enumerated() {
                // 在每次循环之前等待 300 毫秒
                let delayTime = DispatchTime.now() + .milliseconds(index * 300)
                dispatchQueue.asyncAfter(deadline: delayTime) {
                    let hexString = item
                    let byte = self.hexStringToBytes(hexString)!
                    let data = Data(bytes: byte, count: byte.count)
                    self.connectedPeripheral!.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
                }
            }
        }
    }
    // 返回到阈值设置页面
    func setTyreThresholeFun() {
        setTyreThresholeNum = setTyreThresholeNum + 1
        print ("需要返回阈值设置页面了")
        print(setTyreThresholeNum)
        print(bindList)
        if setTyreThresholeNum == carTyreBindNum {
            // 获取上一页面的视图控制器
            if let previousVC = navigationController?.viewControllers[1] as? HamatonCarTyreViewController {
                // 调用上一页面的设置成功的方法
                previousVC.thresholdSettingSuccess()
            }
            // 返回上一页面
            navigationController?.popViewController(animated: false)
        }
    }
    // 获取所有已绑定的轮胎位号
    func getAllTyrePosition(_ data: Data?) {
        currentTrailer = 1
        allBindTyreData = []
        let count = Int(data!.count)
        carTyreBindNum = count
        var tyreArray = [String]()
        for index in 1..<count {
            tyreArray.append(String(format: "%02X", data![index]))
        }
        // 创建一个 DispatchQueue 用于执行循环任务
        let dispatchQueue = DispatchQueue.global()
        for (index, item) in tyreArray.enumerated() {
            // 在每次循环之前等待 300 毫秒
            let delayTime = DispatchTime.now() + .milliseconds(index * 300)
            dispatchQueue.asyncAfter(deadline: delayTime) {
                self.getTyreSensor(item)
            }
        }
    }
    
    // 获取轮胎传感器--轮胎展示页面
    func getTyreSensor(_ tyreNum: String) {
        print("获取轮胎传感器了")
        getTyreTpmsClickType = 5
        let hexString = "48" + tyreNum
        let byte = self.hexStringToBytes(hexString)!
        let data = Data(bytes: byte, count: byte.count)
        self.connectedPeripheral!.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
        currentTrailer = currentTrailer + 1
    }
    
     // 刷新轮胎展示页数据
    func goTyreDisplay(_ data: Data?) {
        allBindTyreData.append(data!)
        if currentTrailer == carTyreBindNum {
            print("该跳转页面啦")
            let vc = HamatonTyreDisplayViewController()
            vc.hidesBottomBarWhenPushed = true
            vc.allBindTyreData = allBindTyreData
            vc.carType = String(equipmentData![5])
           // vc.delegate = self
            self.navigationController?.pushViewController(vc, animated: false)
        }
    }
    
    // 固件升级
    func firmwareUpgradeSave0(_ url: URL) {
        print("升级升级升级")
        do {
            // 文件地址
            selectedFileURL = url
            // 升级第一步
            firmwareUpgradeSave1()
        } catch {
            print("无法读取文件数据：\(error.localizedDescription)")
        }
    }
    // 固件升级第一步——配置版本号
    func firmwareUpgradeSave1() {
        let hexString = "0B01020304"
        let byte = self.hexStringToBytes(hexString)!
        let data = Data(bytes: byte, count: byte.count)
        self.connectedPeripheral!.writeValue(data, for: self.characteristicUp!, type: CBCharacteristicWriteType.withResponse)
    }
    // 固件升级第二步——发送开始
    func firmwareUpgradeSave2() {
        let hexString = "00"
        let byte = self.hexStringToBytes(hexString)!
        let data = Data(bytes: byte, count: byte.count)
        self.connectedPeripheral!.writeValue(data, for: self.characteristicUp!, type: CBCharacteristicWriteType.withResponse)
    }
    // 固件升级第三步——传输文件
    func firmwareUpgradeSave3() {
        do {
            let chunkSize = 200 // 传输的每个数据块的大小
            var offset = 0
            let url = self.selectedFileURL ?? URL(string: "")!
            let data = try Data(contentsOf: url)
            var idx = 0
            fileUpNum = data.count/chunkSize + 1
            while offset < data.count {
                let chunk = data.subdata(in: offset..<min(offset + chunkSize, data.count))
                self.connectedPeripheral!.writeValue(chunk, for: self.characteristicUp2!, type: CBCharacteristicWriteType.withResponse)
                // 添加延时，控制传输速率
                usleep(150000) // 延时 150 毫秒
                offset += chunkSize
                idx = idx + 1
                print(idx)
                if fileUpNum == idx {
                    print("循环结束啦")
                    let operationQueue = OperationQueue()
                    let delayInSeconds = 1.0
                    let blockOperation = BlockOperation {
                        // 延时后执行的代码
                        print("This message is printed after a 2-second delay in OperationQueue.")
                        self.firmwareUpgradeSave4()
                    }

                    DispatchQueue.global().asyncAfter(deadline: .now() + delayInSeconds) {
                        operationQueue.addOperation(blockOperation)
                    }
                }
            }
        } catch {
            // 处理错误
            print("An error occurred: \(error)")
        }
        
    }
    // 固件升级第四步——发送结束
    func firmwareUpgradeSave4() {
        let byte:[UInt8] = [0x03]
        let data = Data(bytes: byte, count: byte.count)
        self.connectedPeripheral!.writeValue(data, for: self.characteristicUp!, type: CBCharacteristicWriteType.withResponse)
    }
    // 固件升级第五步——发送校验
    func firmwareUpgradeSave5() {
        print("发送校验了！！")
        let byte:[UInt8] = [0x0A]
        let data = Data(bytes: byte, count: byte.count)
        self.connectedPeripheral!.writeValue(data, for: self.characteristicUp!, type: CBCharacteristicWriteType.withResponse)
    }
    // 固件升级第六步——发送执行
    func firmwareUpgradeSave6() {
        let byte:[UInt8] = [0x0D]
        let data = Data(bytes: byte, count: byte.count)
        self.connectedPeripheral!.writeValue(data, for: self.characteristicUp!, type: CBCharacteristicWriteType.withResponse)
        print("升级完成了！！！")
        // 获取上一页面的视图控制器
        if let previousVC = self.navigationController?.viewControllers.last as? HamatonFirmwareUpgradeViewController {
            // 调用上一页面的刷新数据方法
            previousVC.upgradeSuccess()
        }
    }
    // 固件升级成功后断开连接
    func upgradeSuccessDisconnect() {
        navigationController?.popViewController(animated: false)
        self.disconnectLink()
    }
    
    // 获取显示器设置参数
    func getXsqSettingInfo(_ data: Data?) {
        xianshiqiInfo = data
        currentClickType = 6
        // 获取头车MAC地址的请求
        let hexString = "4700"
        print("请求头车MAC")
        let byte = self.hexStringToBytes(hexString)!
        let data = Data(bytes: byte, count: byte.count)
        self.connectedPeripheral!.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
    }
    
    // 获取头车MAC地址 bool=true 有头车MAC bool=false 没有头车MAC
    func getToucheMACAddress(_ data: Data?, _ bool: Bool) {
        let yalidanwei = String(format: "%02X", xianshiqiInfo![3])
        let wendudanwei = String(format: "%02X", xianshiqiInfo![4])
        let xiumianshijian = Int(String(format: "%02X", xianshiqiInfo![6]), radix: 16)
        let shengyinbaojing = String(format: "%02X", xianshiqiInfo![7])
        let guacheshuliang = Int(String(format: "%02X", xianshiqiInfo![1]), radix: 16)
        var toucheMacStr = ""
        if bool {
            toucheMacStr = String(format: "%02X", data![1]) + String(format: "%02X", data![2]) + String(format: "%02X", data![3]) + String(format: "%02X", data![4]) + String(format: "%02X", data![5]) + String(format: "%02X", data![6])
            toucheMacStr = String(toucheMacStr.replacingOccurrences(of: ":", with: "").groupCharactersByTwoWithColon())
        }
        let vc = HamatonXsqDisplayViewController()
        vc.hidesBottomBarWhenPushed = true
        vc.xsqDisplaySettingModel.yalidanweiStr = yalidanwei
        vc.xsqDisplaySettingModel.wendudanweiStr = wendudanwei
        vc.xsqDisplaySettingModel.xiumianshijianStr = String(xiumianshijian!)
        vc.xsqDisplaySettingModel.shengyinbaojingStr = shengyinbaojing
        vc.xsqDisplaySettingModel.guacheshuliangStr = String(guacheshuliang!)
        vc.xsqDisplaySettingModel.toucheMACStr = toucheMacStr
        vc.delegate = self
        self.navigationController?.pushViewController(vc, animated: false)
    }
    
    // 显示器保存设置
    func xsqDisplaySave(_ xsqModel: XsqDisplaySettingModel) {
        var hexString = "30"
        let guacheshuliangStr = decimalToHexadecimal2(xsqModel.guacheshuliangStr)
        let zidongxuexiStr = "01"
        let yalidanweiStr = xsqModel.yalidanweiStr
        let wendudanweiStr = xsqModel.wendudanweiStr
        let lunwenchaoshiStr = "06"
        let xiumianshijianStr = decimalToHexadecimal2(xsqModel.xiumianshijianStr)
        let shengyinbaojingStr = xsqModel.shengyinbaojingStr
        let otherStr = "0A4000380000000000"
        xianshiqiMac = xsqModel.toucheMACStr // 显示器MAC地址备用，保存完基础设置调用setToucheMac保存头车MAC
        hexString = hexString + guacheshuliangStr + zidongxuexiStr + yalidanweiStr + wendudanweiStr + lunwenchaoshiStr + xiumianshijianStr + shengyinbaojingStr + otherStr
        let byte = self.hexStringToBytes(hexString)!
        let data = Data(bytes: byte, count: byte.count)
        self.connectedPeripheral!.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
    }
    
    // 设置头车MAC
    func setToucheMac() {
        print("显示器设置成功了，要设置头车MAC了")
        if(xianshiqiMac == "") { // 擦除头车MAC
            let hexString = "4500"
            let byte = self.hexStringToBytes(hexString)!
            let data = Data(bytes: byte, count: byte.count)
            self.connectedPeripheral!.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
        } else { // 设置头车MAC
            let xsqMacStr = xianshiqiMac.replacingOccurrences(of: ":", with: "")
            let hexString = "4400" + xsqMacStr
            let byte = self.hexStringToBytes(hexString)!
            let data = Data(bytes: byte, count: byte.count)
            self.connectedPeripheral!.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
        }
        
    }
    // 显示器设置成功
    func setDisplaySuccess() {
        // 获取上一页面的视图控制器
        if let previousVC = navigationController?.viewControllers.last as? HamatonXsqDisplayViewController {
            // 调用上一页面的刷新数据方法
            previousVC.macSettingSuccess()
        }
    }
}


extension HamatonDeviceViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return discoveredPeripheralsArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "HamatonBluetoothTitleTableViewCell", for: indexPath) as! HamatonBluetoothTitleTableViewCell
        if indexPath.row >= 0 && indexPath.row < discoveredPeripheralsArr.count {
            let model: HamatonBluethoothCellModel = discoveredPeripheralsArr[indexPath.row]
            cell.cellModel = model
        }
        cell.delegate = self
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }
    
    
}
extension HamatonDeviceViewController: HamatonBluetoothTitleTableViewCellDelegate {
    func hamatonBluetoothTitleTableViewCellLink(model: HamatonBluethoothCellModel?) {
        if (model?.peripheral) != nil {
            let macStr = model?.mac ?? ""
            self.connectBluetooth(peripheral: model?.peripheral, mac: macStr)
        }
    }
}

extension HamatonDeviceViewController: HamatonDeviceConnectedViewDelegate {
    // 修改设备名称
    func editDeviceNameAlert() {
        // 获取当前设备名称
        let byte:[UInt8] = [0x35]
        let data = Data(bytes: byte, count: 1)
        for byte in 0..<data.count {
            print("\(byte)")
        }
        self.connectedPeripheral!.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
        
    }
    // 车辆设置
    func carSettingViewShow()  {
        print("车辆设置")
        currentClickType = 1
        // 获取当前接收机配置信息
        let byte:[UInt8] = [0x34]
        let data = Data(bytes: byte, count: 1)
        self.connectedPeripheral!.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
    }
    // 获取挂车数量
    func getTrailerNum() {
        // 查询学习参数
        let byte:[UInt8] = [0x43]
        let data = Data(bytes: byte, count: 1)
        print("获取学习参数")
        self.connectedPeripheral!.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
    }
    // 设备诊断
    func diagnosisAlertShow()  {
        let byte:[UInt8] = [0x3A]
        let data = Data(bytes: byte, count: 1)
        for byte in 0..<data.count {
            print("\(byte)")
        }
        self.connectedPeripheral!.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
    }
    // 车辆轮胎设置页
    func carTyreViewShow() {
        print("车辆轮胎设置")
        currentClickType = 2
        // 查询车辆类型
        let byte:[UInt8] = [0x34]
        let data = Data(bytes: byte, count: 1)
        self.connectedPeripheral!.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
    }
    // 获取轮胎位号
    func getTyrePosition() {
        let byte:[UInt8] = [0x40]
        let data = Data(bytes: byte, count: 1)
        self.connectedPeripheral!.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
    }
    
    // 固件升级
    func firmwareUpgradeViewShow() {
        // 获取当前版本 然后跳转到固件升级页面
        let byte:[UInt8] = [0x36]
        let data = Data(bytes: byte, count: 1)
        self.connectedPeripheral!.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
    }
    
    // 跳转到固件升级页面
    func goUpgradeView(_ data: Data?) {
        let data8 = String(format: "%02X", data![8])
        let data9 = String(format: "%02X", data![9])
        let data10 = String(format: "%02X", data![10])
        let editionStr = data8 + "." + data9 + "." + data10
        let vc = HamatonFirmwareUpgradeViewController()
        vc.hidesBottomBarWhenPushed = true
        vc.editionStr = editionStr
        vc.delegate = self
        self.navigationController?.pushViewController(vc, animated: false)
    }
    
    // 车辆轮胎展示
    func carTyreDisplayViewShow() {
        currentClickType = 3
        self.view.makeToastActivity(.center)
        // 延时执行时间，单位为秒
        let delayInSeconds: TimeInterval = 2.0
        DispatchQueue.main.asyncAfter(deadline: .now() + delayInSeconds) {
            // 在延时之后清除提示
            self.view.hideToastActivity()
        }
        // 获取当前接收机配置信息
        let byte:[UInt8] = [0x34]
        let data = Data(bytes: byte, count: 1)
        self.connectedPeripheral!.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
    }
    
    // 显示器设置
    func xsqDisplayViewShow() {
        currentClickType = 6
        let hexString = "34"
        let byte = self.hexStringToBytes(hexString)!
        let data = Data(bytes: byte, count: 1)
        self.connectedPeripheral!.writeValue(data, for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
    }
}

